from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.template.loader import get_template
from django.shortcuts import render_to_response
from django.http import HttpResponse,Http404
from django.template import Context
from books.models import Book
from mysite001.forms import ContactForm
import datetime
def hello(request):
    return HttpResponse("Hello world")

def current_url_view_good(request):
    return HttpResponse("welcome to page of %s"%request.path)

def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    #assert False
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

def display_meta(requset):
    values = requset.META.items()
    values.sort()
    return render_to_response("display_meta.html",locals())

# def search_form(request):
#     return render_to_response('search_form.html')

def search(request):
    errors = []
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            errors.append('Enter a search term.')
        elif len(q) > 20:
            errors.append('Please enter at most 20 characters.')
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html',
            {'books': books, 'query': q})
    return render_to_response('search_form.html', {'error': errors})

# def contact(request):
#     errors = []
#     if request.method == 'POST':
#         if not request.POST.get('subject',''):
#             errors.append('Enter a subject')
#         if not request.POST.get('message', ''):
#             errors.append('Enter a message.')
#         if request.POST.get('email') and '@' not in request.POST['email']:
#             errors.append('Enter a valid e-mail address.')
#         if not errors:
#             send_mail(
#             request.POST['subject'],
#             request.POST['message'],
#             request.POST.get('email', 'noreply@example.com'),
#             ['siteowner@example.com'],
#             )
#             return HttpResponseRedirect('/contact/thanks/')
#     return render_to_response('contact_form.html',
#     {'errors': errors,
#      'subject':request.POST.get('subject', ''),
#      'message': request.POST.get('message', ''),
#      'email':request.POST.get('email', ''),}
#     )

def thanks(request):
    return render_to_response('thanks.html', {'user1':'zodiac','user2':'gemini'})

def contact(request):
    if  request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleand_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                    ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render_to_response('contact_form.html', {'form': form})

def method_splitter(request,GET = None,POST = None):
    if request.method == 'GET' and GET is not None:
        return GET(request)
    elif request.method == 'POST' and POST is not None:
        return POST(request)
